import logging
import os

# App Engine imports
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template

from db import Games

logging.getLogger().setLevel(logging.INFO)

class Admin:
  """Initializes the list of gifts in the datastore."""

  def getGames(self):
    names = []
    for game in Games.all():
      names.append(game.name)
    return names


class AdminServer(webapp.RequestHandler):
  """Handles requests to /admin URLs and delegates to the Admin class."""

  def _handleRequest(self):
    """Invokes methods from the Admin class based on the 'action' parameter"""
    admin = Admin()
    action = self.request.get('action')
    if action == 'list':
      self.response.out.write("Games = %s" % admin.getGames())              
    elif action == 'addgame':
      template_values = {
            'greetings': 'hello kamal'
       }
      path = os.path.join(os.path.dirname(__file__),'addgame.html')
      self.response.out.write(template.render(path,template_values))
    else:
      html = []
      html.append('<a href="/admin?action=list">List all Games</a>')
      html.append('<a href="/admin?action=addgame">Add Game</a>')
      self.response.out.write(''.join(html))

  def get(self):
    """Ensure that the user is an admin, then invoke appropriate action."""
    if not users.GetCurrentUser():
      loginUrl = users.CreateLoginURL(self.request.uri)
      self.response.out.write('<a href="%s">Login</a>' % loginUrl)
      return

    if not users.IsCurrentUserAdmin():
      self.response.out.write('You must be an admin to view this page.')
      return

    self._handleRequest()

  def post(self):
    if not users.GetCurrentUser():
      loginUrl = users.CreateLoginURL(self.request.uri)
      self.response.out.write('<a href="%s">Login</a>' % loginUrl)
      return
    if not users.IsCurrentUserAdmin():
      self.response.out.write('You must be an admin to view this page.')
      return
    games = Games()
    games.name = self.request.get('gamename')
    games.src = self.request.get('src')
    games.rstatus = True
    games.put()
    self.response.out.write('Game Added Successfully!!!')